package com.guigusuqi.app.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.guigusuqi.commonutils.vo.Result;
import com.guigusuqi.app.service.MsmService;
import com.guigusuqi.app.utils.RandomUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@Api(tags = {"wx-发送短信息管理"})
//@CrossOrigin
public class MsmController
{
    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public Result sendMsm(@PathVariable String phone) throws TencentCloudSDKException
    {
        //从redis中获取验证码如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return Result.success();
        }
        //2、如果获取不到进行腾讯云发送
        //生成随机值，实现发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service中的方法实现短信的发送
        boolean isSend = msmService.send(code,phone);
        if (isSend){
            //如果发送成功那么就将其放入redis中
            redisTemplate.opsForValue().set(phone,code,10, TimeUnit.MINUTES);
            return Result.success();
        }else {
            return Result.fail().message("短信发送失败");
        }

    }

    // 验证短信验证码是否填写正确
    // 注册
    @PostMapping("verify/{openid}/{code}/{phone}")
    public Result registerUser(@PathVariable String openid,@PathVariable String code,@PathVariable String phone){
        boolean verify = msmService.verify(openid, code, phone);
        if (verify){
            return Result.success().message("验证成功");
        }else {
            return Result.success().message("验证失败");
        }
    }


}

